package com.woniu.core.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniu.core.entity.CoreCompensation;
import com.woniu.core.entity.CoreEnterprise;
import com.woniu.core.entity.CoreRecourse;
import com.woniu.core.entity.CoreUser;
import com.woniu.core.entity.vo.CoreCompensationVO;
import com.woniu.core.entity.vo.CoreRecourseVO;
import com.woniu.core.mapper.CoreCompensationMapper;
import com.woniu.core.mapper.CoreEnterpriseMapper;
import com.woniu.core.mapper.CoreRecourseMapper;
import com.woniu.core.mapper.CoreUserMapper;
import com.woniu.core.service.CoreCompensationService;
import com.woniu.finance.entity.Asset;
import com.woniu.finance.entity.Finance;
import com.woniu.finance.entity.Tender;
import com.woniu.finance.mapper.AssetMapper;
import com.woniu.finance.mapper.FinanceMapper;
import com.woniu.finance.mapper.TenderMapper;
import com.woniu.util.utils.HttpResult;
import com.woniu.util.utils.RequestParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 核心企业代偿功能
 */
@Service
public class CoreCompensationServiceImpl implements CoreCompensationService {

    @Autowired
    private TenderMapper tenderMapper;
    @Autowired(required = false)
    private CoreCompensationMapper compensationMapper;

    @Autowired(required = false)
    private CoreEnterpriseMapper enterpriseMapper;

    @Autowired(required = false)
    private FinanceMapper financeMapper;

    @Autowired(required = false)
    private AssetMapper assetMapper;

    @Autowired(required = false)
    private CoreRecourseMapper recourseMapper;

    @Autowired(required = false)
    private CoreUserMapper coreUserMapper;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    /**
     *
     * 待处理追偿项目
     */
    public HttpResult<?> findCompensationById(String coreUserAccount) {
        QueryWrapper<CoreUser> userQuery = new QueryWrapper<>();
        userQuery.eq("account", coreUserAccount);
        CoreUser user = coreUserMapper.selectOne(userQuery);
        QueryWrapper<Tender> query = new QueryWrapper<>();
        query.eq("overdue_compensation", 1)
                .eq("core_id", user.getUserCoreId());
        List<Tender> tenders = new ArrayList<Tender>();
        tenders = tenderMapper.selectList(query);
        List<CoreCompensationVO> waitToCompensation = new ArrayList<>();
        if (tenders.size() > 0) {
            for (Tender tender : tenders) {
                String fName = financeMapper.selectById(tender.getFinanceId()).getEnterpriseName();//获得融资企业名
                Asset assets = assetMapper.selectById(tender.getAssetId());//获取融资抵押物信息
                BigDecimal compensationValue = tender.getRepaymentAmount();//待还金额
                Timestamp RepaymentTime = Timestamp.valueOf(tender.getFinalRepaymentTime());//原待还时间
                CoreCompensationVO wait = new CoreCompensationVO(fName, assets.getAssetName(), assets.getCargoValue(), RepaymentTime, compensationValue);
                waitToCompensation.add(wait);
            }
            return new HttpResult<>().ok(waitToCompensation);
        } else {
            return new HttpResult<>().fail();
        }
    }

    @Override
    /**
     * 代偿
     */
    public HttpResult<?> doCompensation(Integer tenderId) {
        Tender tender = tenderMapper.selectById(tenderId);
//        去重.防止重复标的插入
        QueryWrapper<CoreCompensation> queryWrap = new QueryWrapper<>();
        queryWrap.eq("tender_id", tenderId);
        CoreCompensation check = compensationMapper.selectById(queryWrap);
        if (tender != null && check == null) {
            CoreCompensation compensation = new CoreCompensation();
//            录入核心企业id
            compensation.setCoreId(tender.getCoreId());
//            录入标的id
            compensation.setTenderId(tenderId);
//            录入待换金额
            compensation.setCompensationValue(tender.getRepaymentAmount());
//            录入抵押的资产id
            compensation.setCollateralAssetsId(tender.getAssetId());
            compensation.setCompensationTime(Timestamp.valueOf(sdf.format(new Date())));
            compensationMapper.insert(compensation);
            tender.setOverdueCompensation(2);
            tenderMapper.updateById(tender);
            //抵押货物价值与代偿金额进行对比
            Asset asset = assetMapper.selectById(tender.getAssetId());
            if (asset.getCargoValue().compareTo(compensation.getCompensationValue()) < 1) {
                CoreEnterprise enterprise = enterpriseMapper.selectById(compensation.getCoreId());
                enterprise.setEnterpriseFunds(enterprise.getEnterpriseFunds().subtract(compensation.getCompensationValue().subtract(asset.getCargoValue())));
                enterprise.setFrozenCapital(enterprise.getFrozenCapital().add(compensation.getCompensationValue().subtract(asset.getCargoValue())));
                enterpriseMapper.updateById(enterprise);
            } else {
                CoreRecourse recourse = new CoreRecourse();
                recourse.setAssetsId(tender.getAssetId());
                recourse.setAssetsTrueValue(asset.getCargoValue());
                recourse.setCompensationValue(compensation.getCompensationValue());
                recourse.setRemainingAmount(asset.getCargoValue().subtract(compensation.getCompensationValue()));
                recourse.setCoreId(tender.getCoreId());
                recourseMapper.insert(recourse);
            }
            return new HttpResult<>().ok();
        } else {
            return new HttpResult<>().fail();
        }
    }

    /**
     * 查询代偿记录
     *
     * @param requestParam
     * @return
     */
    @Override
    public HttpResult<?> checkCompensation(RequestParam<String> requestParam) {
        List<CoreCompensationVO> compensationsVO = new ArrayList<>();
        String aName = requestParam.getData();
        String coreId = coreUserMapper.selectUserCoreIdByUserAccount(aName);
        QueryWrapper<CoreCompensation> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("compensation_time")
                .eq("core_id", coreId);
        PageHelper.startPage(requestParam.getPageNum(), requestParam.getPageSize());
        List<CoreCompensation> compensations = compensationMapper.selectList(queryWrapper);
        PageInfo pageInfo = new PageInfo(compensations);
        for (CoreCompensation c : compensations) {
            String tId = tenderMapper.selectById(c.getTenderId()).getFinanceId();
            String financeName = financeMapper.selectById(tId).getEnterpriseName();
            Asset asset = assetMapper.selectById(c.getCollateralAssetsId());
            CoreCompensationVO cVO = new CoreCompensationVO(financeName, asset.getAssetName(), asset.getCargoValue(), c.getCompensationTime(), c.getCompensationValue());
            compensationsVO.add(cVO);
        }
        pageInfo.setList(compensationsVO);
        return new HttpResult<>().ok(pageInfo);
    }
}
